package huaweiod.second;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 跳马问题 真TM恶心
 * https://renjie.blog.csdn.net/article/details/135018519
 */
public class C14_JumpHouseProblem {

    public static int[][] dir = {{1, 2}, {2, 1}, {-1, -2}, {-2, -1}, {1, -2}, {2, -1}, {-1, 2}, {-2, 1}};
    public static int n;
    public static int m;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = Integer.parseInt(in.next());
        m = Integer.parseInt(in.next());
        // 各个节点能到距离
        int[][] path = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                path[i][j] = Integer.MIN_VALUE;
            }
        }

        List<int[]> house = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // 输入每个节点，节点到每个位置的遍历
                String point = in.next();
                if (".".equals(point)) {
                } else {
                    int rest = Integer.parseInt(point);
                    house.add(new int[]{i, j, rest});
                    for (int i1 = 0; i1 < n; i1++) {
                        for (int j1 = 0; j1 < m; j1++) {
                            int dfs = dfs(i, j, rest, 0, i1, j1);
                            path[i1][j1] = Math.max(path[i1][j1], dfs);
                        }
                    }
                }
            }
        }
        int ans = Integer.MAX_VALUE;
        int minI = 0;
        int minJ = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (path[i][j] < ans) {
                    ans = path[i][j];
                    minI = i;
                    minJ = j;
                }
            }
        }
        if (ans == Integer.MAX_VALUE) {
            System.out.println(0);
        } else {
            int res = 0;
            for (int[] ints : house) {
                res += dfs(ints[0], ints[1], ints[2], 0, minI, minJ);
            }
            System.out.println(res);
        }
    }

    // (i,j)到(x,y)还有k步的最小距离
    public static int dfs(int i, int j, int rest, int count, int x, int y) {
        if (i == x && j == y) {
            return count;
        }
        // 越界处理
        if (i < 0 || i >= n || j < 0 || j >= m || rest == 0) {
            return Integer.MAX_VALUE;
        }
        int ans = Integer.MAX_VALUE;
        for (int k = 0; k < dir.length; k++) {
            int next = dfs(i + dir[k][0], j + dir[k][1], rest - 1, count + 1, x, y);
            ans = Math.min(ans, next);
        }
        return ans;
    }

}